package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());

        log.info("走到这里了0");

        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        log.info("走到这里了1");

        //判断当前用户是否为新用户
        User user = userMapper.getByOpenid(openid);

        log.info("走到这里了2");

        //如果是新用户，自动完成注册
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);//后绪步骤实现
        }

        log.info("走到这里了3");

        //返回这个用户对象
        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        // 1. 打印参数，确认配置正确
        log.info("appid: {}", weChatProperties.getAppid());
        log.info("secret: {}", weChatProperties.getSecret());
        log.info("code: {}", code);
        log.info("请求地址: {}", WX_LOGIN);

        // 2. 构建参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        // 3. 发送请求并打印完整响应
        String json;
        try {
            json = HttpClientUtil.doGet(WX_LOGIN, map);
            log.info("微信接口返回: {}", json); // 关键：打印完整响应
        } catch (Exception e) {
            log.error("请求微信接口失败", e);
            return null;
        }

        // 4. 解析响应，处理错误码
        JSONObject jsonObject = JSON.parseObject(json);
        if (jsonObject.containsKey("errcode")) {
            int errCode = jsonObject.getIntValue("errcode");
            String errMsg = jsonObject.getString("errmsg");
            log.error("微信接口返回错误: errcode={}, errmsg={}", errCode, errMsg);
            return null;
        }

        // 5. 获取openid
        String openid = jsonObject.getString("openid");
        log.info("获取到openid: {}", openid);
        return openid;
    }
}